using Adnc.Application.Shared;
using Adnc.Infra.Core;
using Adnc.Shared.RpcServices.Services;
using Autofac;
using Hangfire;
using WYT.Ord.Application.EventSubscribers;

namespace WYT.Ord.WebApi
{
    public class Startup
    {
        private readonly IHostEnvironment _environment;

        private IServiceCollection _services;

        private readonly IConfiguration _config;


        public Startup(IHostEnvironment environment, IConfiguration config)
        {
            _environment = environment;
            _config = config;            
        }

        public void ConfigureServices(IServiceCollection services)
        {
            _services = services;
            services.AddWYTServices(registion => {
                var policies = registion.GenerateDefaultRefitPolicies();
#if DEBUG
                registion.AddRpcService<IUserRpcService>("https://gateway.wyuntao.com", policies);
                registion.AddRpcService<IProductRPCService>("https://gateway.wyuntao.com", policies);
                registion.AddRpcService<IPayRpcService>("https://gateway.wyuntao.com", policies);
                registion.AddEventBusSubscribers();
#else
                registion.AddRpcService<IUserRpcService>("wyt.usr.webapi", policies);
                registion.AddRpcService<IProductRPCService>("wyt.pro.webapi", policies);
                registion.AddRpcService<IPayRpcService>("wyt.pay.webapi", policies);
                registion.AddEventBusSubscribers<CapEventSubscriber>();
#endif
                registion.AddHangfire();
            });

            services.Configure<ERPOptions>(_config.GetSection("ERP"));
        }

        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterAdncModules(_services);
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseAdncMiddlewares();

            var serviceInfo = app.ApplicationServices.GetService<IServiceInfo>();
            app.UseHangfireDashboard(serviceInfo);

            RecurringJob.AddOrUpdate<OrdHangfireJobService>(x => x.ReceivingCheck(), Cron.Hourly(), TimeZoneInfo.Local);

            if (_environment.IsProduction() || _environment.IsStaging())
            {
                app.RegisterToConsul();
            }
        }
    }
}
